package com.songlanyun.common.config.resttplconfig;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.crypto.symmetric.AES;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

@Component
public class RegisterComponent {
    private final static String KEY = "songlanyunaeskey20991001";
    private final static String PREFIX = "songlanyun";


    @Value("${sly.reg.code}")
    private String code;

    @PostConstruct
    public void init() throws Exception {
        validateCode();
    }

    public Boolean isExpire(String dateStr) {
        DateTime parse = DateUtil.parse(dateStr, "yyyy-MM-dd");
        Date date = new Date();
        return date.compareTo(parse)>0;
    }

    public void validateCode() throws Exception {
        String[] split = decCode();

        if(!PREFIX.equals(split[0]))
        {
            throw new Exception("启动key违法");
        }

        if(isExpire(split[1]))
        {
            throw new Exception("项目过期");
        }
    }

    private String[] decCode() {
        AES aes = SecureUtil.aes(KEY.getBytes());
        String decContent = aes.decryptStr(code);
        return decContent.split("\\|");
    }


    public static void main(String[] args) {
        String content = "songlanyun|2099-12-30";
        String key ="songlanyunaeskey20991001";
        AES aes = SecureUtil.aes(key.getBytes());
        String encryptHex = aes.encryptHex(content);
        String decContent = aes.decryptStr(encryptHex);
        System.out.println(encryptHex);
        System.out.println(decContent);
    }
}
